//index.js
//获取应用实例
const app = getApp()
var util = require('../../utils/util.js')
Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    pass:0,
    is_autoplay:false,
    rule:true,
    is_time:true,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },

    close:function () {
       this.setData({
           is_time:!this.data.is_time
       })
    },
    //游戏规则
    ruleTap:function () {
       this.setData({
           rule:!this.data.rule
       })
    },
    //广告跳转
    avdtap:function (e) {
        wx.navigateToMiniProgram({
            appId: e.currentTarget.dataset.appid,
            path: 'pages/index/index',
            success:function(res) {
                console.log(res)
            }
        })
    },
    //天鱼游戏盒子
    float:function () {
        wx.navigateToMiniProgram({
            appId: "wxaa3e45e4b6a1bbd0",
            path: 'pages/index/index',
            success:function(res) {
                console.log(res)
            }
        })
    },
  onLoad: function () {
      wx.getSystemInfo({
          success: function(res) {
              console.log(res.platform)
              app.globalData.platform = res.platform;
          }
      })
    if (app.globalData.userInfo) {
      this.login()
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.login()
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.login()
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
    this.adver()
    this.listFriends()
    this.datachuli()
      
  },
  datachuli:function () {
        var that = this
        wx.request({
            url: 'https://res7.sanliwenhua.com/picture.json',
            header: {
                'content-type': 'application/json' // 默认值
            },
            success: function (res) {
                console.log(res.data)
                var data = res.data
                wx.request({
                    url: 'https://res7.sanliwenhua.com/1-15.json',
                    header: {
                        'content-type': 'application/json' // 默认值
                    },
                    success: function (res1) {
                        console.log(res1.data.easy)
                        var data1 = res1.data.easy
                        var easy = []
                        for(var i=0;i<data1.length;i++){
                            for(var y=0;y<data.length;y++){
                                if(data1[i].word == data[y].answer){
                                    data1[i].pic = data[y].pic
                                    data1[i].word = data[y].word
                                    data1[i].answer = data[y].answer
                                    //console.log(data1[i])
                                    easy.push(data1[i])
                                }
                            }
                        }
                        app.globalData.easy = []
                        app.globalData.easy = easy
                        that.setData({
                            easy:easy,
                        })
                    }
                })
                wx.request({
                    url: 'https://res7.sanliwenhua.com/16-25.json',
                    header: {
                        'content-type': 'application/json' // 默认值
                    },
                    success: function (res1) {
                        console.log(res1.data.middle)
                        var data1 = res1.data.middle
                        var middle = []
                        for(var i=0;i<data1.length;i++){
                            for(var y=0;y<data.length;y++){
                                if(data1[i].word == data[y].answer){
                                    data1[i].pic = data[y].pic
                                    data1[i].word = data[y].word
                                    data1[i].answer = data[y].answer
                                    //console.log(data1[i])
                                    middle.push(data1[i])
                                }
                            }
                        }
                        app.globalData.middle = []
                        app.globalData.middle = middle
                        that.setData({
                            middle:middle,
                        })
                    }
                })
                wx.request({
                    url: 'https://res7.sanliwenhua.com/26-30_.json',
                    header: {
                        'content-type': 'application/json' // 默认值
                    },
                    success: function (res1) {
                        //JSON.parse(res1.data)
                        console.log(res1.data)
                        var data1 = res1.data.hard
                        var hard = []
                        for(var i=0;i<data1.length;i++){
                            for(var y=0;y<data.length;y++){
                                if(data1[i].word == data[y].answer){
                                    data1[i].pic = data[y].pic
                                    data1[i].word = data[y].word
                                    data1[i].answer = data[y].answer
                                    //console.log(data1[i])
                                    hard.push(data1[i])
                                }
                            }
                        }
                        app.globalData.hard = []
                        app.globalData.hard = hard
                        that.setData({
                            hard:hard,
                        })
                    }
                })

            }
        })

    },
  //最新的20位选手接口
  listFriends:function () {
        var that = this
        wx.request({
            url: 'https://caige1.sanliwenhua.com/program/new_users?app=7',
            method: "get",
            success: function (res) {
                if (res.data.code = 200) {
                    console.log(res.data)
                    var listFriends = res.data.data;
                    that.setData({
                        listFriends: listFriends
                    })
                }
            }
        })
    },
  //广告接口
  adver:function () {
      var that = this
        wx.request({
            url: 'https://caige1.sanliwenhua.com/program/column?app=7',
            method: "get",
            success: function (res) {
                //console.log(res, "广告")
                if (res.data.code = 200) {
                    var data = res.data.data;
                    var AdvData = []
                    var gameData=[]
                    for(var i = 0;i<data.length;i++){
                        if(data[i].type=="advs"){
                            AdvData.push(data[i])
                        }
                    }
                    for(var i = 0;i<data.length;i++){
                        if(data[i].type=="game"){
                            gameData.push(data[i])
                        }
                    }
                   console.log(AdvData,gameData)
                    that.setData({
                        avdUrl: AdvData,
                        gameData:gameData
                    })
                }
            }
        })
        /*wx.request({
            url: 'https://caige1.sanliwenhua.com/switch',
            method: "get",
            success: function (res) {
                //console.log(res, "开关")
                if (res.data.code = 200) {
                    var isADV = res.data.data.isADV;
                    that.setData({
                        isADV: isADV //广告开关写死
                    })
                } else {

                }
            }
        })*/
        
    },
  //更多好玩的跳转
  ShoppingMallTap: function () {
        wx.navigateToMiniProgram({
            appId: 'wxaa9104bb31aa9b96',
            path: 'pages/index/index',
            envVersion: 'release',
            success: function (res) {
                //console.log(res);
            },
            fail: function (res) {
                //console.error(res);
                wx.showToast({
                    title: res.data.message,
                    image: '/image/errIcon.png',
                    duration: 2000
                })
            }
        })
    },
  //登录接口
  login:function () {
        var that = this
        console.log(app.globalData)
        // wx.showLoading({
        //     title: '加载中...',
        // })
        if(app.globalData.userInfo){
            var dataSend = {
                code: app.globalData.code,
                encryptedData: app.globalData.encryptedData,
                iv: app.globalData.iv,
                icon: app.globalData.userInfo.avatarUrl,
                nickname: app.globalData.userInfo.nickName
            }
            console.log(app.globalData.code)
            wx.request({
                url: 'https://caige1.sanliwenhua.com/program/wx/onLogin?app=7',
                method: "get",
                data: dataSend,
                success: function (res) {
                    console.log(res)
                    if(res.data.code == 200){
                        var token = res.data.data.x_token;
                        var pass = res.data.data.values.pass;
                        var userid = res.data.data.values.user_id;
                        var frequency = res.data.data.values.frequency;
                        var id =  res.data.data.id;
                        var session_key = res.data.data.session_key;
                        app.globalData.userInfo.token = token;
                        app.globalData.userInfo.frequency = frequency;
                        app.globalData.userInfo.pass = pass;
                        app.globalData.userInfo.id = id;
                        app.globalData.userInfo.userid = userid
                        app.globalData.userInfo.session_key = session_key;
                        //that.update()
                        that.setData({
                            pass: pass
                        })
                        wx.hideLoading()
                        that.resetChallengeObj()
                        if(that.data.is_autoplay&& app.globalData.ChallengeObj.ChallengeTime > 0){
                            that.setData({
                                is_autoplay: false,
                            })
                            //that.resetChallengeObj()
                            setTimeout(function(){
                                wx.navigateTo({
                                    url: '../Details/Details'
                                })
                            },1000)

                        }
                    }
                },
                fail:function (res) {
                    wx.showToast({
                        title: res.data.message,
                        icon: 'success',
                        duration: 2000
                    })
                }
            })
        }
    },
  //闯关机会处理
  resetChallengeObj:function () {
        var that = this
        var myTime = new Date();
        var today = myTime.getDate();
        wx.getStorage({
            key: 'ChallengeObj',
            success: function (res) {
                var ChallengeObj = JSON.parse(res.data)
                //console.log('ChallengeObj', ChallengeObj)
                if (today != ChallengeObj.day) {
                    ChallengeObj = {
                        day: today,
                        ChallengeTime: 3
                    }
                }
                wx.setStorage({
                    key: 'ChallengeObj',
                    data: JSON.stringify(ChallengeObj)
                })
                app.globalData.ChallengeObj = ChallengeObj
                that.setData({
                    ChallengeTime:ChallengeObj.ChallengeTime
                })

            }, fail: function (res) {
                //console.log(res)
                var ChallengeObj = {
                    day: today,
                    ChallengeTime: 3
                }
                wx.setStorage({
                    key: 'ChallengeObj',
                    data: JSON.stringify(ChallengeObj)
                })
                app.globalData.ChallengeObj = ChallengeObj
                that.setData({
                    ChallengeTime:ChallengeObj.ChallengeTime
                })
            }
        })
    },
  //闯关机会处理添加
  AddresetChallengeObj:function () {
        var that = this
        var myTime = new Date();
        var today = myTime.getDate();
        wx.getStorage({
            key: 'ChallengeObj',
            success: function (res) {
                var ChallengeObj = JSON.parse(res.data)
                //console.log('ChallengeObj', ChallengeObj)
                if (today != ChallengeObj.day) {
                    ChallengeObj = {
                        day: today,
                        ChallengeTime: 3
                    }
                }else{
                    ChallengeObj = {
                        day: today,
                        ChallengeTime: ChallengeObj.ChallengeTime+1
                    }
                }
                wx.setStorage({
                    key: 'ChallengeObj',
                    data: JSON.stringify(ChallengeObj)
                })
                app.globalData.ChallengeObj = ChallengeObj
                that.setData({
                    ChallengeTime:ChallengeObj.ChallengeTime
                })

            }, fail: function (res) {
                //console.log(res)
                var ChallengeObj = {
                    day: today,
                    ChallengeTime: 3
                }
                wx.setStorage({
                    key: 'ChallengeObj',
                    data: JSON.stringify(ChallengeObj)
                })
                app.globalData.ChallengeObj = ChallengeObj
                that.setData({
                    ChallengeTime:ChallengeObj.ChallengeTime
                })
            }
        })

    },
  //获取群id接口
  update:function () {
      var that = this
      var NewTime = new Date().getTime().toString();
      var key = util.sha1(app.globalData.userInfo.id + NewTime + app.globalData.userInfo.checkpoint + app.globalData.userInfo.id);
      key = key.toUpperCase()
      var data = {}
      console.log('update群场景shareTicket:',app.globalData)
      var update = function (data) {
          wx.request({
              url: 'https://caige1.sanliwenhua.com/idiom/update_checkpoint',
              method: "post",
              data: data,
              success: function (res) {
                  console.log(res)
                  app.globalData.group_id = res.data.group_id;
              },
              fail: function (res) {
                  console.log(res)
                  wx.showToast({
                      title: res.data.message,
                      icon: 'success',
                      duration: 2000
                  })
              }
          })
      }
      if(app.globalData.shareTicket){
          wx.getShareInfo({
              shareTicket:app.globalData.shareTicket,
              success:function (res) {
                  console.log(res)
                  app.globalData.Sharing= {}
                  app.globalData.Sharing.errMsg = res.errMsg
                  app.globalData.Sharing.encryptedData = res.encryptedData
                  app.globalData.Sharing.iv = res.iv
                  console.log(app.globalData.Sharing)
                  data = {
                      key: key,
                      time: NewTime,
                      checkpoint: app.globalData.userInfo.checkpoint,
                      x_token: app.globalData.userInfo.token,
                      errMsg: res.errMsg,
                      encryptedData: res.encryptedData,
                      iv: res.iv,
                      session_key: app.globalData.userInfo.session_key
                  }
                  update(data);
              },
              fail:function (res) {
                  wx.showToast({
                      title: res.data.message,
                      icon: 'success',
                      duration: 2000
                  })
              }
          })
      }else{
          data = {
              key: key,
              time: NewTime,
              checkpoint: app.globalData.userInfo.checkpoint,
              x_token: app.globalData.userInfo.token
          }
          update(data);
      }
  },
  //点击登录按钮
  getUserInfo: function(e) {
    console.log(e)
     this.setData({
         is_autoplay:true
     })
      /*wx.showLoading({
          title: '加载中...',
      })*/
      if(e.detail.userInfo){
          app.globalData.userInfo = e.detail.userInfo
          this.login()
          this.setData({
              userInfo: e.detail.userInfo,
              hasUserInfo: true
          })
      }
  },
    onShow:function () {
        wx.showShareMenu({
            withShareTicket: true
        })
        if(app.globalData.userInfo){
            //this.update()
            this.setData({
                userInfo: app.globalData.userInfo,
                hasUserInfo: true,
                pass: app.globalData.userInfo.pass,
                ChallengeTime: app.globalData.ChallengeObj.ChallengeTime
            })
        }
    },
    getShare:function (e,a) {
        var that = this
        var data = {}
        wx.getShareInfo({
            shareTicket:e,
            success:function (res) {
                console.log(res)
                data = {
                    x_token: app.globalData.userInfo.token,
                    encryptedData: res.encryptedData,
                    iv: res.iv,
                }
                console.log("传递的参数:",data)
                wx.request({
                    url: 'https://caige1.sanliwenhua.com/program/shars?app=7',
                    method: "get",
                    data: data,
                    success: function (res) {
                        console.log("分享返回:",res.data)
                        if(res.data.code==200){
                            if(a=="qiuzhu"){
                                wx.showModal({
                                    title: "求助成功!",
                                    content: "正确答案:"+that.data.answer,
                                    showCancel: false,
                                    confirmText: "确定"
                                })
                            }else{
                                that.setData({
                                    is_time:!that.data.is_time
                                })
                                that.AddresetChallengeObj()
                                /*setTimeout(function(){
                                    wx.navigateTo({
                                        url: '../Details/Details'
                                    })
                                },1000)*/
                            }
                        }else{
                            wx.showModal({
                                title: "提示",
                                content: "要分享到不一样的群才可以哦",
                                showCancel: false,
                                confirmText: "确定"
                            })
                        }
                    },
                    fail: function (res) {
                        console.log(res)
                        wx.showToast({
                            title: res.data.message,
                            icon: 'success',
                            duration: 2000
                        })
                    }
                })
            },
            fail:function (res) {
                wx.showToast({
                    title: res.data.message,
                    icon: 'success',
                    duration: 2000
                })
            }
        })
    },
    onShareAppMessage: function (e) {
        var that = this;
        var nickeName = app.globalData.userInfo.nickName;
        console.log(e)
        if (e.from === 'button') {
            if(e.target.dataset.type == "tiaozhan"){
                return {
                    title: '['+nickeName+'@我],那些年学过的成语，还记得吗？快来挑战吧！',
                    path: 'pages/index/index',
                    imageUrl: 'http://paz0eiqln.bkt.clouddn.com/image/fenxing2.jpg',
                    success: function (res) {
                        console.log('分享到群的标记', res)
                        if(res.shareTickets){

                            that.getShare(res.shareTickets[0],e.target.dataset.type)
                        }else{
                            wx.showModal({
                                title: "提示",
                                content: "分享到微信群才可以哦！",
                                showCancel: false,
                                confirmText: "确定"
                            })
                        }
                    },
                    fail: function (res) {
                        wx.showToast({
                            title: '分享失败！',
                            image: '/image/errIcon.png',
                            duration: 2000
                        })
                    }
                }
            }

        }else{
            return {
                title: '['+nickeName+'@我],那些年学过的成语，还记得吗？快来挑战吧！',
                path: 'pages/index/index',
                imageUrl: 'http://paz0eiqln.bkt.clouddn.com/image/fenxing.jpg',
                success: function (res) {
                    wx.showToast({
                        title: '分享成功!',
                        icon: 'success',
                        duration: 2000
                    })
                },
                fail: function (res) {
                    wx.showToast({
                        title: '分享失败！',
                        image: '/image/errIcon.png',
                        duration: 2000
                    })
                }
            }

        }
    }
})
